package com.jinly.ryder.common.web;

import com.jinly.ryder.common.error.ErrorException;
import com.jinly.ryder.common.error.ErrorInfo;
import com.jinly.ryder.common.error.SystemErrorType;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.Arrays;
import java.util.stream.Collectors;

@Slf4j
@Order
@RestControllerAdvice
public class ErrorControllerAdvice {

    @ExceptionHandler(ConstraintViolationException.class)
    public ResponseEntity<ErrorInfo> error400Handler(ConstraintViolationException e, HandlerMethod handlerMethod) {
        String msg = e.getConstraintViolations().stream().map(ConstraintViolation::getMessage).collect(Collectors.joining(","));
        ErrorInfo errorInfo = new ErrorInfo(String.valueOf(HttpStatus.BAD_REQUEST.value()), msg);
        return buildResponse(errorInfo, HttpStatus.BAD_REQUEST, e, handlerMethod);
    }

    @ExceptionHandler(MissingServletRequestParameterException.class)
    public ResponseEntity<ErrorInfo> error400Handler(MissingServletRequestParameterException e, HandlerMethod handlerMethod) {
        ErrorInfo errorInfo = new ErrorInfo(String.valueOf(HttpStatus.BAD_REQUEST.value()), e.getMessage());
        return buildResponse(errorInfo, HttpStatus.BAD_REQUEST, e, handlerMethod);
    }

    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    public ResponseEntity<ErrorInfo> error400Handler(MethodArgumentTypeMismatchException e, HandlerMethod handlerMethod) {
        ErrorInfo errorInfo = new ErrorInfo(String.valueOf(HttpStatus.BAD_REQUEST.value()), e.getMessage());
        return buildResponse(errorInfo, HttpStatus.BAD_REQUEST, e, handlerMethod);
    }

    @ExceptionHandler(BindException.class)
    public ResponseEntity<ErrorInfo> error400Handler(BindException e, HandlerMethod handlerMethod) {
        ErrorInfo errorInfo = new ErrorInfo(String.valueOf(HttpStatus.BAD_REQUEST.value()), e.getMessage());
        return buildResponse(errorInfo, HttpStatus.BAD_REQUEST, e, handlerMethod);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<ErrorInfo> error400Handler(MethodArgumentNotValidException e, HandlerMethod handlerMethod) {
        ErrorInfo errorInfo = new ErrorInfo(String.valueOf(HttpStatus.BAD_REQUEST.value()), e.getMessage());
        return buildResponse(errorInfo, HttpStatus.BAD_REQUEST, e, handlerMethod);
    }

    @ExceptionHandler(IllegalArgumentException.class)
    public ResponseEntity<ErrorInfo> error400Handler(IllegalArgumentException e, HandlerMethod handlerMethod) {
        ErrorInfo errorInfo = new ErrorInfo(String.valueOf(HttpStatus.BAD_REQUEST.value()), e.getMessage());
        return buildResponse(errorInfo, HttpStatus.BAD_REQUEST, e, handlerMethod);
    }

    @ExceptionHandler(ErrorException.class)
    public ResponseEntity<ErrorInfo> errorHandler(ErrorException e, HandlerMethod handlerMethod) {
        ErrorInfo errorInfo = e.getErrorInfo();
        boolean isSystemError = Arrays.stream(SystemErrorType.values()).anyMatch(systemError -> systemError.getErrCode().equals(e.getErrorInfo().getErrCode()));
        printLog(errorInfo, e, handlerMethod);
        if (isSystemError) {
            return new ResponseEntity<>(errorInfo, HttpStatus.valueOf(Integer.parseInt(e.getErrorInfo().getErrCode())));
        }
        return new ResponseEntity<>(errorInfo, HttpStatus.BAD_REQUEST);
    }

    @ExceptionHandler(Throwable.class)
    public ResponseEntity<ErrorInfo> error500Handler(Throwable e, HandlerMethod handlerMethod) {
        ErrorInfo errorInfo = new ErrorInfo(String.valueOf(HttpStatus.INTERNAL_SERVER_ERROR.value()), SystemErrorType.INTERNAL_SERVER_ERROR.getErrMsg());
        return buildResponse(errorInfo, HttpStatus.INTERNAL_SERVER_ERROR, e, handlerMethod);
    }

    private ResponseEntity<ErrorInfo> buildResponse(ErrorInfo errorInfo, HttpStatus httpStatus, Throwable e, HandlerMethod handlerMethod) {
        printLog(errorInfo, e, handlerMethod);
        ResponseEntity<ErrorInfo> responseEntity = ResponseEntity.status(httpStatus).body(errorInfo);
        return responseEntity;
    }


    public void printLog(ErrorInfo errorInfo, Throwable e, HandlerMethod handlerMethod) {
        StackTraceElement stackTrace = getLastStackTrace();
        Logger thisLog = log;
        if (stackTrace != null) {
            thisLog = LoggerFactory.getLogger(stackTrace.getClassName());
        }
        String methodKey = handlerMethod.getBeanType().getSimpleName() + "#" + handlerMethod.getMethod().getName();
        if ("500".equals(errorInfo.getErrCode())) {
            thisLog.error("[{}]: {}", methodKey, errorInfo, e);
        }
    }

    private StackTraceElement getLastStackTrace() {
        StackTraceElement[] trace = Thread.currentThread().getStackTrace();
        boolean preIsThis = false;
        for (StackTraceElement stackTraceElement : trace) {
            boolean isThis = stackTraceElement.getClassName().startsWith(this.getClass().getPackage().getName());
            if ((!isThis) && preIsThis) {
                return stackTraceElement;
            }
            preIsThis = isThis;
        }
        return null;
    }
}